package ee.falcon.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;

import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.util.Iterator;
import javax.xml.*;
import javax.xml.namespace.NamespaceContext;

public class Demo4 
{
private DocumentBuilderFactory dbf;
private DocumentBuilder builder;
private Document doc; 
private XPathFactory factory; 
private XPath xpath; 
private XPathExpression expr; 
private TransformerFactory tf;
private Transformer t; 


   public Demo4() throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException
	{
        dbf = DocumentBuilderFactory.newInstance();
        //never forget this
        dbf.setNamespaceAware(true);
        builder = dbf.newDocumentBuilder();
        doc = builder.parse("src/loginProfiles/xml_read_write/profileInfo.xml");
        //System.out.println(document);
        factory = XPathFactory.newInstance();
        
        xpath = factory.newXPath();
        xpath.setNamespaceContext(new MineNamespaceContext());
        //The XPath object compiles the XPath expression: 
        //xpath.setNamespaceContext(new PersonalNamespaceContext());
        expr = xpath.compile("//fal:profiles");
        
        //XPathExpression expr2 = xpath.compile("//fal:profile[@profileId='12']");
        /*
        InputSource xml = new InputSource(new FileReader("src/xml_read_write/profileInfo.xml"));
        String result = expression.evaluate(xml);
        System.out.println(result);
*/		
        Object result1 = expr.evaluate(doc, XPathConstants.NODE);
		Node node1 = (Node) result1;
		//---------------------------------------------------
		XPathFactory factory2 = XPathFactory.newInstance();
        
        XPath xpath2 = factory2.newXPath();
        xpath2.setNamespaceContext(new MineNamespaceContext());
        //The XPath object compiles the XPath expression: 
        //xpath.setNamespaceContext(new PersonalNamespaceContext());
        
        XPathExpression expr2 = xpath.compile("//fal:profile[@fal:profileId='13']");
		
		Object result2 = expr2.evaluate(doc, XPathConstants.NODE);
		Node node2 = (Node) result2;
		
		System.out.println(node1.getNodeName());
		System.out.println(node2.getNodeName());//getFirstChild().getTextContent());
		
		node1.removeChild(node2);
		
		//kustutamise muudatuste tavalise javasse sisseehitatud doc toetava xml-iga kirjutamine
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("src/xml_read_write/profileInfo.xml"));
 
		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
 
		transformer.transform(source, result);
 
		System.out.println("File saved!");
 
	  
	
		//node1.removeChild(node2);
        
        /*Object result = expr.evaluate(doc, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		System.out.println(nodes.getLength());
		for (int i = 0; i < nodes.getLength(); i++) 
		{
			System.out.println(nodes.item(i)); 
		}
        */
       /* b13Node = (Node) expression.evaluate(document, XPathConstants.NODE); 
        b13Node.getParentNode().removeChild(b13Node);

        tf = TransformerFactory.newInstance();
        t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
        */
	}    
}

/**
 * A class to return the appropriate Namespace context
 * for xPath execution against KML files
 */
class MineNamespaceContext implements NamespaceContext 
{
 
  /**
   * A method to return the Namespace URI of a given
   * namespance prefix
   *
   * @param prefix the prefix to math
   *
   * @return       the matched namespace URI
   */
  public String getNamespaceURI(String prefix) 
  {
    // determine which namespace to return
    if (prefix == null) 
    {
      // no prefix specified
      throw new NullPointerException("Null prefix");
    } 
    else if ("fal".equals(prefix)) 
    {
      // fal ehk falcon namespace
      return "http://code.google.com/p/nemp-svn/";
    } 
    else if ("atom".equals(prefix)) 
    {
      // atom namespace
      return "http://www.w3.org/2005/Atom";
    }
    else if ("xml".equals(prefix)) 
    {
      // default namespace
      return XMLConstants.XML_NS_URI;
    } 
    else 
    {
      // default namespace
      return XMLConstants.XML_NS_URI;
    }
  }
 
  /**
   * This method isn't necessary for XPath processing.
   */
  public String getPrefix(String uri) 
  {
    throw new UnsupportedOperationException();
  }
 
  /**
   * This method isn't necessary for XPath processing.
   */
  public Iterator getPrefixes(String uri) {
    throw new UnsupportedOperationException();
  }
 
}

